package com.applet.task;

import com.applet.mapper.ActivityMapper;
import com.applet.pojo.entity.Activity;
import com.applet.service.ActivityService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author “XuShao”
 * @date 2024/12/19 22:10
 * @description
 */
@Slf4j
@Component
public class ActivityTask {
    
    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityService activityService;

    @Scheduled(fixedDelay = 60000)
    public void monitorActivityStatus() {
        log.info("=== 监听活动状态 ===");

        // 获取未开始的活动
        List<Activity> activities1 = activityMapper.selectList(new LambdaQueryWrapper<Activity>()
                .eq(Activity::getState, Activity.HAVE_NOT_STARTED)
        );

        // 获取进行中的活动
        List<Activity> activitie2 = activityMapper.selectList(new LambdaQueryWrapper<Activity>()
                .eq(Activity::getState, Activity.UNDERWAY)
        );

        List<Activity> activities = activities1.stream()
                .filter(activity -> LocalDateTime.now().isAfter(activity.getBeginTime()))
                .map(activity -> activity.setState(Activity.UNDERWAY)).toList();

        activityService.updateBatchById(activities);

        activities = activitie2.stream()
                .filter(activity -> LocalDateTime.now().isAfter(activity.getEndTime()))
                .map(activity -> activity.setState(Activity.CANCELED)).toList();

        activityService.updateBatchById(activities);
    }
}
